package com.example.leetcode.solution;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution930 {

    public static void main(String[] args) {
        int[] nums = new int[]{0,0,0,0,0,0,1,0,0,0};
        int i = new Solution930().numSubarraysWithSum2(nums, 1);
        System.out.println(i);
    }

    public int numSubarraysWithSum(int[] nums, int goal) {
        int sum = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            List<Integer> array = new ArrayList<>();
            sum = nums[i];
            array.add(nums[i]);
            if (sum == goal) {
                count++;
//                System.out.println(sum);
            }
            for (int j = i + 1; j < nums.length; j++) {
                int temp = sum + nums[j];
                if(temp > goal){
                    break;
                }
                if (temp == goal) {
                    sum = temp;
                    array.add(nums[j]);
                    count++;
//                    array.forEach(integer -> {
//                        System.out.print(integer + "\t");
//                    });
//                    System.out.println();
                } else if (temp < goal) {
                    sum = temp;
                    array.add(nums[j]);
                }
            }
        }
        return count;
    }


    public int numSubarraysWithSum2(int[] nums, int goal) {
        int sum = 0;
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
        int ret = 0;
        for (int num : nums) {
            cnt.put(sum, cnt.getOrDefault(sum, 0) + 1);
            sum += num;
            ret += cnt.getOrDefault(sum - goal, 0);
        }
        return ret;
    }

}
